package com.bipbip.repositorio;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.bipbip.modelo.Usuario;
import com.bipbip.modelo.Vehiculo;

@Repository(value = "vehiculoDao")
@Transactional(readOnly = true)
public class JPAVehiculoDAOImpl implements VehiculoDAO {

	private EntityManager em = null;

	/*
	 * Sets the entity manager.
	 */
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public Vehiculo insert(Vehiculo v) {
		em.persist(v);
		return v;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public Vehiculo update(Vehiculo v) {
		return em.merge(v);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void delete(Vehiculo v) {
		v.setDeleted(true);
		update(v);
	}

	@Transactional(readOnly = true)
	public Vehiculo select(int id) {
		return em.find(Vehiculo.class, id);
	}
	
	@Transactional(readOnly = true)
	public List<Vehiculo> selectAll() {
		return em.createQuery("select v from Vehiculo v").getResultList();
	}


	@Transactional(readOnly = true)
	public List<Vehiculo> selectBy(String attr, String value) {
		return em.createQuery(
				"select v from Vehiculo v where " + attr + "='" + value
						+ "' and isDeleted=0").getResultList();
	}

	public List<Vehiculo> selectBy(String attr, Integer value) {
		return em.createQuery(
				"select v from Vehiculo v where " + attr + "=" + value
						+ " and isDeleted=0").getResultList();
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void delete(Integer id) {
		Vehiculo v = select(id);
		v.setDeleted(true);
		update(v);
	}

	public List<Vehiculo> selectByUser(Usuario user) {
		return selectBy("usuario", user.getId());
	}

}
